package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.cart.client.CartInfoFeignClient;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.user.client.UserInfoFeignClient;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import sun.plugin2.message.Message;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.nio.channels.Channel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderInfoApiController {
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private CartInfoFeignClient cartInfoFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;
    //去结算页面
    @GetMapping("/trade")
    public Map trade(HttpServletRequest request){
        Map result = new HashMap();
        //1.获取收货地址
        List<UserAddress> userAddressList = userInfoFeignClient.getUserAddressList();
        result.put("userAddressList",userAddressList);
        //2.商品清单
        List<CartInfo> cartInfoList = cartInfoFeignClient.getCartInfoListByChecked();
        List<OrderDetail> detailArrayList = cartInfoList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            return orderDetail;
        }).collect(Collectors.toList());
        result.put("detailArrayList",detailArrayList);
        //3.小计
        //3.1:获得购买的商品数量 summarizing 汇总
        long sum = detailArrayList.stream().collect(
                Collectors.summarizingInt(orderDetail -> {
                    return orderDetail.getSkuNum();
                })
        ).getSum();
        //3.2: 获得购买商品的总金额
        BigDecimal totalPrice = new BigDecimal(0); //totalPrice的初始值为1
        for (OrderDetail orderDetail : detailArrayList) {
            BigDecimal onePrice = orderDetail.getOrderPrice().multiply(new BigDecimal(orderDetail.getSkuNum()));
            totalPrice = totalPrice.add(onePrice);
        }
        result.put("totalNum",sum);
        result.put("totalAmount",totalPrice);
        //4.订单号, 交易号 使用uuid
        String userId = AuthContextHolder.getUserId(request);
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("tradeNo:"+userId,uuid);
        result.put("tradeNo",uuid);
        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo,
                              HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1:校验交易号是否正确  不能重复提交
        if (StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("交易号不能为空");
        }else {
            //正确
            Object no = redisTemplate.opsForValue().get("tradeNo:" + userId);
            if (StringUtils.isEmpty(no)){
                //缓存中没有有交易号
                return Result.fail().message("不可以重复提交");
            }else {
                if (!tradeNo.equals(no)){
                    return Result.fail().message("交易号不正确");
                }
            }
        }

        //删除交易号
        redisTemplate.delete("tradeNo:" + userId);
        //2.校验库存
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean isHave = orderInfoService.hasStock(orderDetail);
            if (isHave == false){
                //库存不足
                return Result.fail().message(orderDetail.getSkuName() + "[库存不足]");
            }
        }

        //3.提交订单(保存订单主表,订单详情表)
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.insertOrder(orderInfo);
        return Result.ok(orderId);
    }

    //根据订单id查询订单对象
    @GetMapping("/auth/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }

    //由库存发起的 远程调用订单微服务 要求订单微服务进行拆单
    @PostMapping("/orderSplit")
    public List<Map> orderSplit(Long orderId,String wareSkuMap){
        //wareSkuMap  [{"wareId":"1","skuIds":["2","10"]}    ,{"wareId":"2","skuIds":["3"]}]
        //              wareId 1号仓库ID   skuIds:库存集合     wareId 2号仓库ID  skuIds:库存集合
        //1.开始拆单, 1张订单 拆分后 成n张订单
        List<OrderInfo> subOrderInfoList  //这个是拆分完之后的子订单集合
                = orderInfoService.orderSplit(orderId,wareSkuMap);

        //给库存系统返回值
        List<Map> listMap = subOrderInfoList.stream().map(subOrderInfo -> {
            Map map = orderInfoService.initWareOrder(subOrderInfo);
            return map;
        }).collect(Collectors.toList());
        return listMap;
    }
}